package com.franklin.java.api.classloader;


import java.net.URL;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 根据URL对类加载器隔离，从而对类进行隔离
 * @author Franklin
 * @since 2021/9/24 19:01
 */
public class ExternalJarsClassLoader{

    private static Map<String,ExternalJarClassLoader> jarNameClassLoaderMap = new ConcurrentHashMap<>();

    /**
     * 根据URL加载jar包<br>
     * @author Franklin
     * @since 2021/9/25 10:01
     * @param url:
     * @return void
     */
    public synchronized static void loadJar(URL url){
        ExternalJarClassLoader externalJarClassLoader = jarNameClassLoaderMap.get(url.getPath());
        if (Objects.isNull(externalJarClassLoader)){
            externalJarClassLoader = new ExternalJarClassLoader(url,Thread.currentThread().getContextClassLoader());
            jarNameClassLoaderMap.put(url.getPath(),externalJarClassLoader);
        }
    }

    /**
     * 根据URL获取对应的类加载器<br>
     * @author Franklin
     * @since 2021/9/25 10:01
     * @param url:
     * @return com.franklin.java.api.classloader.ExternalJarClassLoader
     */
    public static ExternalJarClassLoader getClassLoader(URL url){
        ExternalJarClassLoader externalJarClassLoader = jarNameClassLoaderMap.get(url.getPath());
        if (Objects.isNull(externalJarClassLoader)){
            loadJar(url);
            return getClassLoader(url);
        }
        return externalJarClassLoader;
    }
}
